package com.pengshun.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * twitter的snowflake算法
 * @author zhangning
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "env.snow-flake")
public class SnowFlake {

    /**
     * 起始的时间戳
     */
    private final static long START_STMP = 1480166465631L;

    /**
     * 每一部分占用的位数
     */

    private final static long SEQUENCE_BIT = 12;

    private final static long MACHINE_BIT = 5;

    private final static long DATA_CENTER_BIT = 5;

    /**
     * 每一部分的最大值
     */
    private final static long MAX_DATA_CENTER_NUM = -1L ^ (-1L << DATA_CENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATA_CENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATA_CENTER_LEFT + DATA_CENTER_BIT;

    private Long dataCenter;

    private Long machine;
    //序列号
    private long sequence = 0L;
    //上一次时间戳
    private long lastStmp = -1L;



    /**
     * 产生下一个ID
     */
    public synchronized long nextId() {
        long currStmp = getNewStmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;
        /*
         * //时间戳部分
         * //数据中心部分
         * //机器标识部分
         * //序列号部分
         */
        return (currStmp - START_STMP) << TIMESTMP_LEFT
                | dataCenter << DATA_CENTER_LEFT
                | dataCenter << MACHINE_LEFT
                | sequence;
    }

    private long getNextMill() {
        long mill = getNewStmp();
        while (mill <= lastStmp) {
            mill = getNewStmp();
        }
        return mill;
    }

    private long getNewStmp() {
        return System.currentTimeMillis();
    }

}
